package edu.palermo.dondeestoy;

import utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import edu.palermo.dondeestoy.rest.ApiService;

public class Splash extends Activity {

	private static String TAG = "Splash";
	private String imeiActual = "";
	private String idEquipo = "";
	private Utils utils;
	String strBattery="";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash_layout);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

		final TelephonyManager tm = (TelephonyManager) getBaseContext()
				.getSystemService(Context.TELEPHONY_SERVICE);

		utils = new Utils(this);
		
		imeiActual = tm.getDeviceId();
		Log.i(TAG, "IMEI: " + imeiActual);
		
		strBattery="1";
		try
		{
			strBattery=utils.getBatteryLevel();		
			if(strBattery==null)
				strBattery="";
		}catch(Exception e)
		{
			strBattery="";
		}
		Log.i(TAG, "BAttery: " + strBattery);
		
		//String serverAddress = utils.getServerAddress();
		String serverAddress="sharedpc.dyndns-home.com:5125";
		//String serverAddress="192.168.0.29:5125";
		
		Log.i(TAG, "ServerAddress: " + serverAddress);
		//utils.setIdEquipo(idEquipo);
		
		utils.saveIMEI(imeiActual);
		
		utils.saveServerAddress(serverAddress);
		ApiService.setServerAddress(serverAddress);

		Handler x = new Handler();
		x.postDelayed(new SplashHandler(), 2000);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	class SplashHandler implements Runnable {
		public void run() {
			
			try
			{
				idEquipo=utils.getIdEquipo();
				Log.i(TAG, "idEquipo: " + idEquipo);
				
				if((idEquipo!=null)&&(!idEquipo.equals(""))&&(!idEquipo.equals(" ")))
				{
					startActivity(new Intent(getApplication(), MainActivity.class));
				}else
				{
					Log.i(TAG, "StartActivity Initial");
					startActivity(new Intent(getApplication(), InitialSettings.class));
					
				}
			}catch(NullPointerException ex)
			{
				Log.i(TAG, "StartActivity Initial2");
				startActivity(new Intent(getApplication(), InitialSettings.class));
			}catch(Exception e)
			{
				Log.e(TAG, "EXCEPTION: " + e);
			}	
		}

	}
}
